package org.advanced.nio;

import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @author John.zhang
 * @version Id: ZeroCopyServer, v 1.0 2020/12/17 14:48 ZhiYong Exp $
 */
public class ZeroCopyServer {

    public static void main(String[] args) {
        try {
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.socket().bind(new InetSocketAddress(8080));
            //阻塞客户端连接
            SocketChannel socketChannel = serverSocketChannel.accept();
            ByteBuffer byteBuffer = ByteBuffer.allocate(2048);
            int r = 0;
            FileChannel channel = new FileOutputStream("C:/data/io/nio.txt").getChannel();
            while (r!=-1){
                r=socketChannel.read(byteBuffer);
                byteBuffer.flip();
                channel.write(byteBuffer);
                byteBuffer.clear();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭流
        }

    }

}
